package com.atguigu.srb.oss.service.Impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.CannedAccessControlList;
import com.atguigu.srb.oss.service.OssService;
import com.atguigu.srb.oss.utils.OssProperties;
import lombok.extern.slf4j.Slf4j;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.UUID;
@Service
@Slf4j
public class OssServiceImpl implements OssService {
    @Override
    public String upload(InputStream inputStream, String module, String fileName) {

        /**
         * 文件上传至阿里云
         */
            // 创建OSSClient实例。
            OSS ossClient = new OSSClientBuilder().build(
                    OssProperties.ENDPOINT,
                    OssProperties.KEY_ID,
                    OssProperties.KEY_SECRET);
            //判断oss实例是否存在：如果不存在则创建，如果存在则获取
            if(!ossClient.doesBucketExist(OssProperties.BUCKET_NAME)){
                //创建bucket
                ossClient.createBucket(OssProperties.BUCKET_NAME);
                //设置oss实例的访问权限：公共读
                ossClient.setBucketAcl(OssProperties.BUCKET_NAME, CannedAccessControlList.PublicRead);
            }

            //构建日期路径：avatar/2019/02/26/文件名
            String folder = new DateTime().toString("yyyy/MM/dd");

            //文件名：uuid.扩展名
            fileName = UUID.randomUUID().toString() + fileName.substring(fileName.lastIndexOf("."));
            //文件根路径
            String key = module + "/" + folder + "/" + fileName;

            //文件上传至阿里云
            ossClient.putObject(OssProperties.BUCKET_NAME, key, inputStream);

            // 关闭OSSClient。
            ossClient.shutdown();
            log.info("存储完成");
            //阿里云文件绝对路径
            return "https://" + OssProperties.BUCKET_NAME + "." + OssProperties.ENDPOINT + "/" + key;

        }

    @Override
    public void removeFile(String url) {
        // 填写文件完整路径。文件完整路径中不能包含Bucket名称。
        //https://my-srb-20210917.oss-cn-beijing.aliyuncs.com/
        // avatar/2021/09/17/2e6307e0-0b3a-4ee3-b7fa-0d71908c1dc0.xlsx
        String host ="https://"+OssProperties.BUCKET_NAME+"."+OssProperties.ENDPOINT+"/";
        String substring = url.substring(host.length());
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(   OssProperties.ENDPOINT,
                OssProperties.KEY_ID,
                OssProperties.KEY_SECRET);
        // 删除文件或目录。如果要删除目录，目录必须为空。
        ossClient.deleteObject(OssProperties.BUCKET_NAME, substring);
        // 关闭OSSClient。
        ossClient.shutdown();

    }

}
